using EnvDTE;
using EnvDTE80;
using Microsoft.Practices.RecipeFramework;
using VSSDKAssist.Assets.Actions.Base;
using VSSDKAssist.Assets.Helpers;

namespace VSSDKAssist.Recipes.Common.Actions
{
	/// <summary>
	/// Action that inserts an attribute to a CodeClass
	/// </summary>
    public class InsertAttributeToCodeClassAction : ActionBase
	{
        /// <summary>
        /// Gets or sets the attribute name.
        /// </summary>
        /// <value>The attribute name.</value>
        [Input(Required = false)]
        public string AttributeName { get; set; }

        /// <summary>
        /// Gets or sets the attribute.
        /// </summary>
        /// <value>The attribute.</value>
        [Input(Required = true)]
        public string AttributeValue { get; set; }

        private CodeClass codeClass;

        /// <summary>
        /// Gets or sets the code class.
        /// </summary>
        /// <value>The code class.</value>
        [Input(Required = true)]
        public CodeClass CodeClass
        {
            get { return codeClass; }
            set { codeClass = value; }
        }

		/// <summary>
		/// Called when [execute].
		/// </summary>
		protected override void OnExecute()
		{
            if(!string.IsNullOrEmpty(this.AttributeName))
            {
                CodeAttribute2 att = FileCodeModelHelper.GetAttribute(this.CodeClass, this.AttributeName) as CodeAttribute2;

                if(att != null)
                {
                    FileCodeModelHelper.RemoveAttribute(att);
                }
            }

            EditPoint startEditPoint = this.CodeClass.StartPoint.CreateEditPoint();
            EditPoint editPoint = this.CodeClass.EndPoint.CreateEditPoint();

            editPoint.MoveToLineAndOffset(startEditPoint.Line, 1);
            ((EditPoint2)editPoint).InsertNewLine(1);
            editPoint.LineUp(1);
            editPoint.Insert(SanitizeTTTransformation(this.AttributeValue));

            //Re Format inserted text
            startEditPoint.StartOfDocument();
            editPoint.EndOfDocument();

            startEditPoint.SmartFormat(editPoint);		
		}

        private string SanitizeTTTransformation(string stringToSanitize)
        {
            string content = stringToSanitize;

            if(content.EndsWith("\r\n"))
            {
                content = content.Substring(0, content.Length - 2);
            }

            return content;
        }
	}
}